package com.heima.search.service.impl;

import com.heima.common.search.ElasticSearchTemplate;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.search.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.*;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    private ElasticSearchTemplate elasticSearchTemplate;
    @Autowired
    private ApUserSearchService apUserSearchService;
    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        //0.判空
        if (dto==null) {
            return ResponseResult.okResult("");
        }
        //1.入参
        String searchWords = dto.getSearchWords();
        int pageNum = dto.getPageNum();
        int pageSize = dto.getPageSize();
        Date minBehotTime = dto.getMinBehotTime();
        //AppThreadLocalUtil获取id
        Integer userId = AppThreadLocalUtil.getUser().getId();
        if (userId==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //2.查询条件
        //2.1关键字查询
        QueryStringQueryBuilder stringQueryBuilder = elasticSearchTemplate.getStringQueryBuilder(searchWords, Operator.OR, "title", "content");
        //2.2范围查询
        Map<String, Object> condition = new HashMap<>();
        condition.put("lt",minBehotTime);
        RangeQueryBuilder rangeBuilder = elasticSearchTemplate.getRangeBuilder("publishTime", condition);
        //2.3Bool查询
        Map<String, AbstractQueryBuilder> builderMap = new HashMap<>();
        builderMap.put("must",stringQueryBuilder);
        builderMap.put("filter",rangeBuilder);
        BoolQueryBuilder boolQueryBuilder = elasticSearchTemplate.getBoolQueryBuilder(builderMap);
        //3.高亮
        HighlightBuilder highlightBuilder = elasticSearchTemplate.getHighlightBuilder("title", "<font style='color:red;font-size:inherit;'>", "</font>");
        //4.搜索
        SearchResponse search = elasticSearchTemplate.search("app_info_article", boolQueryBuilder, highlightBuilder, pageNum, pageSize, "publishTime", SortOrder.DESC);
        //4.1记录本次搜索的关键字
        apUserSearchService.insert(searchWords,userId);
        SearchHit[] hits = search.getHits().getHits();
        if (ArrayUtils.isEmpty(hits)) {
            return ResponseResult.okResult("");
        }
        List<Map<String, Object>> list = new ArrayList<>();
        for (SearchHit hit : hits) {
            if(hit==null){
                continue;
            }
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            //todo 再看一看
            //*处理高亮显示
            if (!CollectionUtils.isEmpty(highlightFields)) {
                Text[] titles = highlightFields.get("title").getFragments();
                String join = StringUtils.join(titles, ",");
                sourceAsMap.put("h_title",join);
            }else {
                sourceAsMap.put("h_title",sourceAsMap.get("title"));
            }
            list.add(sourceAsMap);
        }
        return ResponseResult.okResult(list);
    }
}
